package model;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;


/**
 * This class is used to parse an xls file. This class does not support
 * xlsx file.
 * 
 * @author Bruce
 */
public class XLSParser extends Parser {

    private Sheet myFirstSheet;

    /**
     * construct XLSParser
     * @param xlsFile file with extension xls
     * @throws IOException input-output exception occured when reading
     */
    public XLSParser (File xlsFile) throws IOException {
        super(xlsFile);
    }

    @SuppressWarnings("rawtypes")
    protected void readData () {
        for (int j = 1; j < myFirstSheet.getRows(); j++) {
            ArrayList<Comparable> rowData = new ArrayList<Comparable>();
            for (int i = 0; i < myFirstSheet.getColumns(); i++) {
                Cell cell = myFirstSheet.getCell(i, j);
                String cellContent = cell.getContents();
                rowData.add(cellContent);
            }
            getTable().add(rowData);
        }
    }

    protected void readCategories (File inputDataFile) throws IOException{
        Workbook myWorkbook = null;
        try {
            myWorkbook = Workbook.getWorkbook(inputDataFile);
        }
        catch (BiffException e) {
            e.printStackTrace();
        }
        catch (IOException e) {  
            System.err.println("Error when reading XLS file");
            throw e;
        }
        // Get the first sheet
        myFirstSheet = myWorkbook.getSheet(0);

        // Get the field names and types
        for (int j = 0; j < myFirstSheet.getColumns(); j++) {
            String content = myFirstSheet.getCell(j, 0).getContents();
            getFieldNames().add(content);
            content = myFirstSheet.getCell(j, 1).getContents();
            getFieldTypes().add(determineType(content));
        }
    }

    @Override
    /**
     * get the table generated from the file
     */
    public Table retrieveTable() {
        Table result = new Table(getTable(), getFieldTypes());
        return result;
    }
}
